package com.controller.base;


import com.common.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseLocalController {

    private final Logger logger = LoggerFactory.getLogger(BaseLocalController.class);

    @ExceptionHandler(RuntimeException.class)
    public void exception(HttpServletRequest request, HttpServletResponse response, RuntimeException e) throws Exception {
        String requestType = request.getParameter("X-Requested-With");
        String ajax = request.getParameter("act");
        /*ajax请求*/
        if (null != requestType || "ajax".equals(ajax)) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            StringBuffer sb0 = new StringBuffer("{\"status\": ").append(ResultUtil.ERROR);
            sb0.append(", \"message\": \"").append("系统错误，请联系系统管理员").append("\"}");
            response.getWriter().write(sb0.toString());
        } else {
            request.getRequestDispatcher("/WEB-INF/views/exception/error.jsp").forward(request, response);
        }
        /*做日志记录*/
        logger.error(e.getMessage(), e);
        e.printStackTrace();
    }

    protected ResultUtil validate(BindingResult error, String... aliases) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (error.hasErrors()) {
            String _$0 = null;
            if (null != aliases && aliases.length > 0) {
                _$0 = aliases[0];
            }
            List<FieldError> fieldErrorList = error.getFieldErrors();
            Map<String, String> errorsMap = new HashMap<>();
            StringBuilder message = new StringBuilder();
            String field;
            String fieldErrorMessage;
            FieldError fieldError;
            int size = fieldErrorList.size();
            for (int i = 0; i < size; i++) {
                fieldError = fieldErrorList.get(i);
                field = fieldError.getField();
                fieldErrorMessage = fieldError.getDefaultMessage();
                errorsMap.put(field, fieldErrorMessage);
                if (null != _$0 && !"".equals(_$0)) {
                    message.append(_$0).append(".");
                }
                message.append(field).append("：").append(fieldErrorMessage);
                if (i != size - 1) {
                    message.append("，");
                }
            }
            /*必填参数验证不通过*/
            resultUtil.setStatus(ResultUtil.PARAM_VALID_FAILED);
            resultUtil.setMessage(message.toString());
            resultUtil.setData(errorsMap);
        }
        return resultUtil;
    }

    protected ResultUtil validate(BindingResult[] errors, String... aliases) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null != errors && errors.length > 0) {
            BindingResult error;
            StringBuilder message = new StringBuilder();
            Map<String, String> errorsMap = new HashMap<>();
            for (int i = 0; i < errors.length; i++) {
                error = errors[i];
                if (error.hasErrors()) {
                    String _$0 = null;
                    if (null != aliases && aliases.length > 0) {
                        _$0 = aliases[i];
                    }
                    List<FieldError> fieldErrorList = error.getFieldErrors();
                    String field;
                    String fieldErrorMessage;
                    FieldError fieldError;
                    int size = fieldErrorList.size();
                    for (int c = 0; c < size; c++) {
                        fieldError = fieldErrorList.get(c);
                        field = fieldError.getField();
                        fieldErrorMessage = fieldError.getDefaultMessage();
                        errorsMap.put(field, fieldErrorMessage);
                        if (null != _$0 && !"".equals(_$0)) {
                            message.append(_$0).append(".");
                        }
                        message.append(field).append("：").append(fieldErrorMessage);
                        if (c != size - 1) {
                            message.append("，");
                        }
                    }
                    /*必填参数验证不通过*/
                    resultUtil.setStatus(ResultUtil.PARAM_VALID_FAILED);
                }
                resultUtil.setMessage(message.toString());
                resultUtil.setData(errorsMap);
            }
        }
        return resultUtil;
    }
}